import time
from locust import HttpUser, task, between, constant, FastHttpUser,constant_throughput
import requests, json
import random

vehicleId_list = [[] for id in range(1000, 7001)]


class QuickstartUser(FastHttpUser):
    # wait_time = constant(0)
    wait_time = constant_throughput(40)

    def on_start(self):
        headers = {
            "Authorization": "",
            "Content-Type": "application/json"
        }
        payload = json.dumps({
            "username": "super_admin",
            "password": "5747cba9d15d3ad80507ed5b3cf84e25",
            "clientId": "frontend",
            "grantType": "password"
        })

        # r = requests.post(url='https://140.206.122.22:9001/v2x/platform/auth/user/login', headers=headers, data=payload,
        #                   verify=False).text
        # r_dict = json.loads(r)
        # self.token = r_dict['data']["accessToken"]
        self.headers = {
            "Authorization": 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NzgzODQ5NzksInVzZXJfbmFtZSI6InN1cGVyX2FkbWluIiwianRpIjoiOTYzNDMwMGQtZDJmYi00OGMwLTg4MjItYjZhYmUyYzJmOGM2IiwiY2xpZW50X2lkIjoiZnJvbnRlbmQiLCJzY29wZSI6WyJhbGwiXX0.iuXV4OJgJOPShTe3_EyHW2j3CRaZDduaJMwd63GJxVU'
        }

    def on_stop(self):
        count = 11
        for i in vehicleId_list:
            print('车辆id为{}的长度:'.format(count), len(i))
            count += 1

    @task(1)
    def lamp1(self):
        vehicleId = random.randint(1000,7000)
        with self.client.post("/v2x/platform/device/road/side/udpSender", json={
            "ip": "140.206.122.22",
            "port": "21000",
            "oemCode": "4B8BC4EC",
            "vehicleId": 'aabbccdd1111{}'.format(str(vehicleId)),
            "token": "48585154",
            "aesKey": "M20YDV7VSPQSYPKS",
            "heading": "300",
            "longitude": "1212134817",
            "latitude": "312916495"
        }, verify=False, headers=self.headers, catch_response=True) as res:
            if res.status_code == 200 and res.json()['status'] == 200:
                res.success()
            else:
                res.failure("Failed")
        vehicleId_list[vehicleId-1000].append(1)
        # print(res.text)


